
from apps.common.base.serializers import *
from apps.interface.pageConfig.models import *
from apps.interface.advert.serializers import AdvertBaseSerializer, AdvertModelSerializer
from apps.interface.node.serializers import Node, NodeModelSerializer

class PageConfigBaseSerializer(BaseSerializer):

    class Meta:
        model = PageConfig
        fields = "__all__"

class PageConfigModelSerializer(BaseSerializer):

    pageeModel = serializers.SerializerMethodField()
    def get_pageeModel(self, obj):
        if obj.pagee:
            return {
                "title": obj.pagee.title,
                "name": obj.pagee.name,
                "path": obj.pagee.path
            }
        else:
            return {}

    clientList = serializers.SerializerMethodField()
    def get_clientList(self, obj):
        return [{'id': obj.id, 'clientname': obj.clientname, 'appname': obj.appname, 'types': obj.types} for obj in obj.clients.all()] if obj.clients else []

    class Meta:
        model = PageConfig
        fields = "__all__"

class PageConfigDetailSerializer(serializers.ModelSerializer):

    pageModel = serializers.SerializerMethodField()
    def get_pageModel(self, obj):
        if obj.pagee:
            return {
                "title": obj.pagee.title,
                "name": obj.pagee.name,
                "path": obj.pagee.path
            }
        else:
            return {}


    advertList = serializers.SerializerMethodField()
    def get_advertList(self, obj):
        adverts = obj.adverts.filter(is_delete=0, isShow=1).order_by('sort', 'id').select_related('cover', 'item')
        if adverts.count()>0:
            return AdvertModelSerializer(adverts, many=True).data
        else:
            return []

    nodeList = serializers.SerializerMethodField()
    def get_nodeList(self, obj):
        nodes = obj.node_PageConfig.all().filter(pageConfig=obj.id, is_delete=0, isShow=1).select_related('component').prefetch_related('adverts', 'adverts__item').order_by('sort','updateTime')
        if nodes.exists():
            return NodeModelSerializer(nodes, many=True).data
        else:
            return []

    class Meta:
        model = PageConfig
        fields = '__all__'